// components/Console/SPICEConsole.tsx
import React, { useEffect, useRef, useState } from 'react';
import { consoleService } from '../../services/console';

interface SPICEConsoleProps {
  connection: string;
  domainName: string;
  className?: string;
}

const SPICEConsole: React.FC<SPICEConsoleProps> = ({
  connection,
  domainName,
  className = ''
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let ws: WebSocket | null = null;

    const connectSPICE = async () => {
      try {
        // 获取SPICE信息
        const spiceInfo = await consoleService.getSPICEInfo(connection, domainName);

        if (!spiceInfo.host || !spiceInfo.port) {
          throw new Error('SPICE connection information not available');
        }

        // 连接spice-html5
        // 1. 创建WebSocket连接
        setLoading(false);
        setError(null);

        // 使用spice-html5库连接(需要安装spice-html5)
        // import * as SpiceHtml5 from 'spice-html5';
        // const spice = new SpiceHtml5.SpiceMainConn({
        //   uri: `ws://${spiceInfo.host}:${spiceInfo.port}`,
        //   screen_id: "spice-screen",
        //   onerror: (e: any) => console.error("SPICE error:", e)
        // });

      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to connect to SPICE console');
        setLoading(false);
      }
    };

    if (connection && domainName) {
      connectSPICE();
    }

    return () => {
      // 清理连接
      if (ws) {
        // 确保 ws 是 WebSocket 类型再调用 close 方法
        if ('close' in ws && typeof (ws as WebSocket).close === 'function') {
          (ws as WebSocket).close();
        }
      }
    };
  }, [connection, domainName]);

  if (loading) {
    return (
      <div className={`flex items-center justify-center h-64 ${className}`}>
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500 mx-auto mb-4"></div>
          <p className="text-gray-500">Connecting to SPICE console...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className={`flex items-center justify-center h-64 ${className}`}>
        <div className="text-center">
          <div className="text-red-500 mb-4">
            <svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <p className="text-red-500 mb-4">{error}</p>
          <p className="text-sm text-gray-500">
            SPICE console requires spice-html5 library integration.
          </p>
          <p className="text-sm text-gray-500">
            Connection info: Host and Port available from API
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className={`relative ${className}`}>
      <div className="bg-black rounded-lg overflow-hidden">
        <div className="p-4 bg-gray-800 text-white text-sm font-mono">
          <div className="flex items-center justify-between mb-2">
            <span>SPICE Console - {domainName}</span>
            <span className="text-green-400">Connected</span>
          </div>
          <div className="text-xs text-gray-400">
            <p>SPICE console integration placeholder</p>
            <p>Install spice-html5 for full functionality</p>
          </div>
        </div>

        {/* 画布区域 */}
        <div className="h-96 bg-black flex items-center justify-center">
          <div className="text-center text-gray-400">
            <div className="mb-4">
              <svg className="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M12 6V3m0 18v-3" />
              </svg>
            </div>
            <p className="text-sm">SPICE Console</p>
            <p className="text-xs text-gray-500">Connection: {connection}</p>
            <p className="text-xs text-gray-500">Domain: {domainName}</p>
          </div>
        </div>
      </div>

      {/* 隐藏的canvas元素(用于SPICE渲染) */}
      <canvas ref={canvasRef} className="hidden" />
    </div>
  );
};

export default SPICEConsole;